// utils.js remains the same

const MagicString = require('magic-string');

// vite-plugin.js
const {
	generateLabelCode,
	getPagesMap,
	initPages,
	getRoute,
} = require('./utils');

let _init = false;
let needHandle = false;
let pagesMap = {};

const myVitePlugin = {
	name: 'vue3-inset-loader',
	transform(code, id) {
		if (!_init) {
			_init = true;
			init(this);
		}

		const route = getRoute(id);
		const curPage = pagesMap[route];

		if ((id.endsWith('.vue') || id.endsWith('.nvue')) && needHandle && curPage) {
			const labelCode = generateLabelCode(curPage.label);

			if (labelCode.length > 0) {
				for (let i = 0; i < labelCode.length; i++) {
					// 判断 labelCode[i] 是不是 object
					if (Object.prototype.toString.call(labelCode[i].ele) === '[object Object]') {
						const templateCode = getTemplateCode(code);
						const sctiptCode = getScriptCode(code);
						const scriptSetupCode = getScriptSetupCode(code);
						const scriptSetupTsCode = getScriptSetupTsCode(code);
						const styleCode = getStyleCode(code);

						code = ``;

						code += `
							<template>
								${templateCode}
								${labelCode[i].ele.template}
							</template>
						`;

						if (sctiptCode) code += `
                            <script>
                                ${sctiptCode}
                            </script>
						`;

						if (scriptSetupCode) code += `
                            <script setup>
                                ${scriptSetupCode}
                                ${labelCode[i].ele.script}
                            </script>
						`;

						if (scriptSetupTsCode) code += `
                            <script lang="ts" setup>
                                ${scriptSetupTsCode}
                                ${labelCode[i].ele.script}
                            </script>
						`;

						code += `
                            <style lang="scss">
                                ${styleCode}
                                ${labelCode[i].ele.style}
                            </style>
						`;
					} else if (labelCode[i].ele === undefined) {
						console.error(`[vue3-inset-loader] ${labelCode[i].label} is undefined`);
					} else {
						console.error(`[vue3-inset-loader] ${labelCode[i].label} is not object`);
					}
				}
			}
		}

		return {
			code,
			map: null // 表示源码视图不作修改
		}

		// if (!id.endsWith('.vue') && !id.endsWith('.nvue')) {
		// 	return null;
		// }
		//
		// if (!needHandle) {
		// 	return null;
		// }
		//
		// const route = getRoute(id);
		// const curPage = pagesMap[route];
		//
		// if (curPage) {
		// 	const labelCode = generateLabelCode(curPage.label);
		//
		// 	if (!labelCode) return null; // 如果没有 labelCode，则不做修改
		//
		// 	const s = new MagicString(code);
		//     const closingTemplateRegex = /<\/template>/g;
		//     let lastClosingTemplateIndex = -1;
		//     let match;
		//
		//     while ((match = closingTemplateRegex.exec(code))) {
		//         lastClosingTemplateIndex = match.index;
		//     }
		//
		//     if (lastClosingTemplateIndex !== -1) {
		//         s.appendRight(lastClosingTemplateIndex, `${labelCode}\n`);
		//     }
		//
		// 	return {
		// 		code: s.toString(),
		// 		map: s.generateMap({ hires: true }), // 生成源映射
		// 	};
		// }
		//
		// return null; // 如果没有对应的 curPage，则不做修改
	},
};

function init(that) {
	needHandle = initPages(that);
	// Convert to a mapping object of routes and configurations
	if (needHandle) {
		pagesMap = getPagesMap();
	}
}

/**
 * 获取代码中的 <template>*</template>内容
 * @param {string} code 源码
 * @returns {string} 返回 <template>*</template>内容
 */
const getTemplateCode = (code) => {
	const templateRegex = /<template>([\s\S]*)<\/template>/;
	const match = code.match(templateRegex);
	return match ? match[1] : '';
}

const getScriptCode = (code) => {
	const scriptRegex = /<script>([\s\S]*)<\/script>/;
	const match = code.match(scriptRegex);
	return match ? match[1] : '';
}

const getScriptSetupCode = (code) => {
	const scriptSetupRegex = /<script setup>([\s\S]*)<\/script>/;
	const match = code.match(scriptSetupRegex);
	return match ? match[1] : '';
}

const getScriptSetupTsCode = (code) => {
	const scriptSetupTsRegex1 = /<script lang="ts" setup>([\s\S]*)<\/script>/;
	const match1 = code.match(scriptSetupTsRegex1);

	if (match1) return match1[1];

	const scriptSetupTsRegex2 = /<script setup lang="ts">([\s\S]*)<\/script>/;
	const match2 = code.match(scriptSetupTsRegex2);

	if (match2) return match2[1];

	return '';
}

const getStyleCode = (code) => {
	const styleRegex = /<style[^>]*>([\s\S]*)<\/style>/;
	const match = code.match(styleRegex);
	return match ? match[1] : '';
}

module.exports = myVitePlugin;